package com.wyzz.hr.bo.impl;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.base.Constants;
import com.wyzz.hr.base.wf.AbstractWorkflow;
import com.wyzz.hr.bo.IEmailsendBO;
import com.wyzz.hr.bo.MimeMailMessageFactory;
import com.wyzz.hr.bo.TemplateService;
import com.wyzz.hr.dao.IEmailsendDAO;
import com.wyzz.hr.pojo.Emailsend;
import com.wyzz.hr.pojo.Emailtemplate;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.SysConfigManager;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

import java.lang.reflect.Method;
import java.util.*;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;

public class EmailsendBoImpl implements IEmailsendBO, Constants {

	public EmailsendBoImpl() {
		dao = null;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setEmailTemplateService(TemplateService emailTemplateService) {
		this.emailTemplateService = emailTemplateService;
	}

	public boolean addEmailsend(Emailsend one) {
		if (StringUtils.isEmpty(one.getEsFrom())) {
			SysConfigManager fileConfigManager = PropertiesFileConfigManager
					.getInstance();
			one.setEsFrom(fileConfigManager.getProperty("email.sys.sender"));
		}
		one.setEsCreatetime(new Date());
		one.setEsStatus(Integer.valueOf(0));
		try {
			dao.saveObject(one);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean delEmailsend(Class name, String id) {
		try {
			dao.deleteObject(name, id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean updateEmailsend(Emailsend one) {
		int esStatus = one.getEsStatus().intValue();
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Emailsend.class);
		detachedCriteria.add(Restrictions.eq(Emailsend.PROP_ID, one.getId()));
		List sendList = dao.findByCriteria(detachedCriteria);
		if (sendList == null || sendList.size() == 0)
			return false;
		Emailsend send;
		for (Iterator it = sendList.iterator(); it.hasNext(); send
				.setEsStatus(Integer.valueOf(esStatus)))
			send = (Emailsend) it.next();

		List errors = sendEmailsMain(sendList);
		return errors == null || errors.size() == 0;
	}

	public boolean updateetStatus(String id, Integer status) {
		Emailtemplate emailtemplte = (Emailtemplate) dao.loadObject(
				com.wyzz.hr.pojo.Emailtemplate.class, id, null, new boolean[0]);
		try {
			if (emailtemplte != null) {
				emailtemplte.setEtStatus(status);
				dao.updateObject(emailtemplte);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public List getListByPager(Emailsend emailsend, Pager page, Date begainC,
			Date endC, Date begainS, Date endS) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Emailsend.class);
		if (emailsend.getEsTo() != null
				&& emailsend.getEsTo().trim().length() > 0)
			detachedCriteria
					.add(Restrictions.like(Emailsend.PROP_ES_TO,
							(new StringBuilder()).append("%").append(
									emailsend.getEsTo().trim()).append("%")
									.toString()));
		if (emailsend.getEsTitle() != null
				&& emailsend.getEsTitle().trim().length() > 0)
			detachedCriteria.add(Restrictions.like(Emailsend.PROP_ES_TITLE,
					(new StringBuilder()).append("%").append(
							emailsend.getEsTitle().trim()).append("%")
							.toString()));
		if (emailsend.getEsStatus() != null)
			detachedCriteria.add(Restrictions.eq(Emailsend.PROP_ES_STATUS,
					emailsend.getEsStatus()));
		if (begainC != null && endC != null)
			detachedCriteria.add(Restrictions.between(
					Emailsend.PROP_ES_CREATETIME, begainC, endC));
		else if (begainC != null)
			detachedCriteria.add(Restrictions.ge(Emailsend.PROP_ES_CREATETIME,
					begainC));
		else if (endC != null)
			detachedCriteria.add(Restrictions.le(Emailsend.PROP_ES_CREATETIME,
					endC));
		if (begainS != null && endS != null)
			detachedCriteria.add(Restrictions.between(
					Emailsend.PROP_ES_SENDTIME, begainS, endS));
		else if (begainS != null)
			detachedCriteria.add(Restrictions.ge(Emailsend.PROP_ES_SENDTIME,
					begainS));
		else if (endS != null)
			detachedCriteria.add(Restrictions.le(Emailsend.PROP_ES_SENDTIME,
					endS));
		BaseAction.addOrders(detachedCriteria, page,
				new String[] { (new StringBuilder()).append(
						Emailsend.PROP_ES_CREATETIME).append("-down")
						.toString() });
		page.splitPage(detachedCriteria);
		List result = dao.findByCriteria(detachedCriteria, page.getPageSize(),
				page.getCurrentPage());
		return result;
	}

	public void updateSendEmailOut() {
		SysConfigManager fileConfigManager = PropertiesFileConfigManager
				.getInstance();
		String pages = fileConfigManager.getProperty("email.send.pages");
		int mailSplit = Integer.valueOf(pages).intValue();
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Emailsend.class);
		detachedCriteria.add(Restrictions.eq(Emailsend.PROP_ES_STATUS, Integer
				.valueOf(0)));
		detachedCriteria.add(Restrictions.isNotNull(Emailsend.PROP_ES_TO));
		detachedCriteria.add(Restrictions.ne(Emailsend.PROP_ES_TO, ""));
		List sendList = dao.findByCriteria(detachedCriteria, mailSplit, 1);
		Emailsend es;
		for (Iterator i$ = sendList.iterator(); i$.hasNext(); es
				.setEsStatus(Integer.valueOf(1)))
			es = (Emailsend) i$.next();

		sendEmailsMain(sendList);
	}

	public void saveAndSendMail(List objList) {
		List esList = new ArrayList();
		Iterator i$ = objList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Object obj = i$.next();
			List mailList = getWorkflow(obj).getSendList();
			if (mailList != null && mailList.size() != 0)
				esList.addAll(mailList);
		} while (true);
		sendEmailsMain(esList);
	}

	public List sendEmailsMain(List esList) {
		List errors = null;
		SysConfigManager fileConfigManager = PropertiesFileConfigManager
				.getInstance();
		String sysEmail = fileConfigManager.getProperty("email.sys.sender");
		List sendMailList = new ArrayList();
		List saveMailList = new ArrayList();
		Date createTime = new Date();
		Iterator it = esList.iterator();
		do {
			if (!it.hasNext())
				break;
			Emailsend es = (Emailsend) it.next();
			if (StringUtils.isEmpty(es.getEsFrom()))
				es.setEsFrom(sysEmail);
			if (es.getEsCreatetime() == null)
				es.setEsCreatetime(createTime);
			if (es.getEsStatus().intValue() == 0) {
				es.setEsStatus(Integer.valueOf(1));
				sendMailList.add(es);
			} else if (es.getEsStatus().intValue() == 1) {
				es.setEsStatus(Integer.valueOf(1));
				sendMailList.add(es);
				saveMailList.add(es);
			} else if (es.getEsStatus().intValue() == 2) {
				es.setEsStatus(Integer.valueOf(0));
				saveMailList.add(es);
			}
		} while (true);
		if (sendMailList.size() > 0)
			errors = sendEmails(sendMailList);
		if (saveMailList.size() > 0)
			dao.saveOrupdate(saveMailList);
		return errors;
	}

	private List sendEmails(List sendEsList) {
		List errors = new ArrayList();
		Map mailMap = new HashMap();
		List mailList = new ArrayList();
		Date sendTime = new Date();
		for (Iterator it = sendEsList.iterator(); it.hasNext();) {
			Emailsend send = (Emailsend) it.next();
			if (StringUtils.isEmpty(send.getEsTo())) {
				logger.info((new StringBuilder()).append(
						"\u90AE\u4EF6\u6536\u4EF6\u4EBA\u4E3A\u7A7A\uFF1A")// 邮件收件人为空
																			// ：
						.append(send).toString());
			} else {
				send.setEsSendtime(sendTime);
				MimeMessage mailMessage = MimeMailMessageFactory
						.createMailMessage(mailSender, send);
				mailMap.put(mailMessage, send);
				mailList.add(mailMessage);
			}
		}

		if (mailMap.size() == 0)
			return errors;
		MimeMessage mailArray[] = (MimeMessage[]) mailList
				.toArray(new MimeMessage[mailMap.size()]);
		boolean connectError = false;
		try {
			mailSender.send(mailArray);
		} catch (MailSendException ex) {
			if (!ex.getFailedMessages().isEmpty()) {
				Map exMap = ex.getFailedMessages();
				Iterator it = exMap.keySet().iterator();
				do {
					if (!it.hasNext())
						break;
					MimeMessage me = (MimeMessage) it.next();
					Emailsend send = (Emailsend) mailMap.get(me);
					if (send != null) {
						send.setEsStatus(Integer.valueOf(2));
						mailMap.remove(me);
						String error = (new StringBuilder())
								.append("\u4ECE")
								.append(send.getEsFrom())
								.append("\u5F80")
								.append(send.getEsTo())
								.append(
										"\u53D1\u9001\u90AE\u4EF6\u5931\u8D25\uFF01")
								.toString();
						logger.info(error);
						errors.add(error);
					}
				} while (true);
			} else {
				String error = "\u670D\u52A1\u5668\u8FDE\u63A5\u5F02\u5E38\uFF01";//服务器连接异常！
				logger.info(error);
				errors.add(error);
				connectError = true;
			}
		} catch (MailException ex) {
			String error = "\u670D\u52A1\u5668\u8FDE\u63A5\u5F02\u5E38:\u90AE\u7BB1\u670D\u52A1\u5668\u7528\u6237\u540D\u6216\u5BC6\u7801\u9519\u8BEF\uFF01";// 服务器连接异常
																																								// :
																																								// 邮箱服务器用户名或密码错误
																																								// ！
			logger.info(error);
			errors.add(error);
			connectError = true;
		}
		if (connectError) {
			Emailsend send;
			for (Iterator it = sendEsList.iterator(); it.hasNext(); send
					.setEsStatus(Integer.valueOf(2)))
				send = (Emailsend) it.next();

		}
		return errors;
	}

	private AbstractWorkflow getWorkflow(Object obj) {
		String methodName = "getWorkflow";
		Class objClass = obj.getClass();
		try {
			Method method = objClass.getMethod(methodName, (Class[]) null);
			return (AbstractWorkflow) method.invoke(obj, (Object[]) null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Emailsend getEmailUser(Map params, Emailtemplate template) {
		Emailsend send = new Emailsend();
		String operEmail = ((Employee) params.get("SENDER")).getEmpEmail();
		String empEmail = ((Employee) params.get("APPLIER")).getEmpEmail();
		if (!StringUtils.isEmpty(empEmail)) {
			send.setEsTo(empEmail);
			send.setEsCc(operEmail);
		} else {
			send.setEsTo(operEmail);
		}
		String content = emailTemplateService.getContent((new StringBuilder())
				.append(template.getEtTitleNo()).append("_body").toString(),
				params);
		String title = emailTemplateService.getContent((new StringBuilder())
				.append(template.getEtTitleNo()).append("_title").toString(),
				params);
		send.setEsTitle(title);
		send.setEsContent(content);
		AbstractWorkflow.setEsStatus(send, template);
		return send;
	}

	public IEmailsendDAO getDao() {
		return dao;
	}

	public void setDao(IEmailsendDAO dao) {
		this.dao = dao;
	}

	private static final Logger logger = Logger
			.getLogger(com.wyzz.hr.bo.impl.EmailsendBoImpl.class);
	private IEmailsendDAO dao;
	private JavaMailSender mailSender;
	private TemplateService emailTemplateService;

}
